package com.mengdie.shuidi.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.blankj.utilcode.utils.LogUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppConfig;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.event.LineEvent;
import com.mengdie.shuidi.event.MainEvent;
import com.mengdie.shuidi.event.MesEvent;
import com.mengdie.shuidi.event.RandomEvent;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.MDModel;
import com.mengdie.shuidi.manager.MDUserMgr;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.model.IpEnetity;
import com.mengdie.shuidi.model.LineEntity;
import com.mengdie.shuidi.model.ModelLine;
import com.mengdie.shuidi.model.UserEnetity;
import com.mengdie.shuidi.model.WeiXingImageEntity;
import com.mengdie.shuidi.ui.activity.MainActivity;
import com.mengdie.shuidi.ui.activity.ProvinceActivity;
import com.mengdie.shuidi.ui.activity.ReplacePhoneActivity;
import com.mengdie.shuidi.ui.interfaces.StatsLineInterface;
import com.mengdie.shuidi.ui.interfaces.StatsLinePresent;
import com.mengdie.shuidi.utils.MDUtil;
import com.mengdie.shuidi.utils.ToastUtil;
import com.mengdie.shuidi.utils.common.EncryptUtils;
import com.mengdie.shuidi.utils.common.TimeUtils;
import com.orhanobut.logger.Logger;
import com.proxy.sosdk.SoError;
import com.proxy.sosdk.SoListener;
import com.proxy.sosdk.SoProxy;
import com.proxy.sosdk.SoState;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.mengdie.shuidi.R.id.ll_ip_reconnect;

/**
 * Created by apple on 16/10/11.
 */

public class HomeFragment extends Fragment {
    private static final String TAG = MainActivity.class.getSimpleName();

    public static final int REQUEST_ROUTE_CODE = 2;

    private static final int START_VPN_PROFILE = 70;

    @Bind(R.id.iv_ip_logo)
    ImageView mIvIpLogo;
    @Bind(R.id.rl_weixin)
    RelativeLayout mRlWeiXin;
    @Bind(R.id.iv_close_weixin)
    ImageView mIVClose;
    @Bind(R.id.rl_ip_top)
    RelativeLayout mRlIpTop;
    @Bind(R.id.tv_validity_time)
    TextView mTvValidityTime;
    @Bind(R.id.tv_line_select)
    TextView mTvLine;
    @Bind(R.id.ll_ip_change)
    LinearLayout mLlIpChange;
    @Bind(R.id.tv_replace_ip)
    TextView mTvReplaceIp;
    @Bind(R.id.ll_validity_time)
    LinearLayout mLlValidityTime;

    @Bind(R.id.rl_ip_start)
    RelativeLayout mRlIpStart;
    @Bind(R.id.iv_ip_start)
    ImageView mIvIpStart;
    @Bind(R.id.ll_ip_break)
    LinearLayout mLlIpBreak;
    @Bind(R.id.ll_ip_reconnect)
    LinearLayout mLlIpReconnect;
    @Bind(R.id.ll_ip_success)
    LinearLayout mLlIpSuccess;
    @Bind(R.id.iv_weixin_icon)
    ImageView mIvWeixinIcon;
    @Bind(R.id.iv_home_kefu)
    ImageView mIvHomeKefu;
    @Bind(R.id.tv_replace_address)
    TextView mTvReplaceAddress;
    @Bind(R.id.rl_go_bind_phone)
    RelativeLayout mRlGoBindPhone;
    private View rootView;
    private boolean isOne = false;
    // 0: 未连接  1:连接成功
    private int mVpnConnectState = 0;


    private String mServerIp = "";
    private int mId;//线路的 id

    private boolean isResume = false;

    private Animation rotate;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private boolean isAlreadyConnect = false;//点击连接  因为  VPN_NOTCONNECTED  走两次


    private static int TIME_OUT = 20000;
    private static final int MSG_CHECK_TIME_OUT = 10001;

    private static final int MSG_VPN_RECONNECT = 10002;
    private static final int MSG_VPN_CONNECT_TIME = 10003;
    private static final int MSG_VPN_GETIP = 10004;
    private int recLen = 0;
    private String newIP = "";
    private String defaultIP = "连接成功";

    private int mProxyType = 1;

    private boolean isRandom = true;//默认是随机获取 ip

    private ModelLine mModelLine;
    private String modelType = "";
    private boolean isStatic = false;
    private UserEnetity userInfo;
    private LineEntity mLine;

    private boolean isConnect = false;
    private boolean isDis;
    private boolean isMobile;
    private boolean isTransit = false;
    private boolean isBtnConnect = true;
    private boolean isSuccess = false;
    private boolean isZhongzhuan = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onStart() {
        super.onStart();
        getUserInfo();
        init();
        if (!isConnect) {
            getIsp();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.activity_home, container, false);
            ButterKnife.bind(this, rootView);
            EventBus.getDefault().register(this);
            getBarHeight();
            checkDis();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CHECK_TIME_OUT:
                    stopAnima();
                    stopVpn();
                    isConnect = false;
                    ToastUtil.showToast("已超时");
                    mTvLine.setEnabled(true);
                    mTvReplaceIp.setVisibility(View.GONE);
                    break;
                case MSG_VPN_RECONNECT:
                    getCheck1();
                    break;
                case MSG_VPN_CONNECT_TIME:
                    recLen--;
                    mTvReplaceIp.setText("正在获取中... " + recLen);
                    if (recLen > 0) {
                        mHandler.sendEmptyMessageDelayed(MSG_VPN_CONNECT_TIME, 1000);
                    } else {
                        sendLog(isSuccess ? "1" : "2", isZhongzhuan ? "1" : "2");
                        getIP();
                    }
                    break;
                case MSG_VPN_GETIP:
                    sendLog(isSuccess ? "1" : "2", isZhongzhuan ? "1" : "2");
                    getIP();
                    break;
            }
            return true;
        }
    });


    @OnClick({R.id.ll_ip_change, R.id.tv_line_select, R.id.ll_ip_break, ll_ip_reconnect,
            R.id.iv_close_weixin, R.id.rl_weixin, R.id.iv_home_kefu, R.id.rl_go_bind_phone, R.id.iv_del})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_line_select://选择线路
//                Intent province = new Intent(getActivity(), LineSelectActivity.class);
                Intent province = new Intent(getActivity(), ProvinceActivity.class);
                startActivity(province);
//                VPNManager.getInstance().stopVpn();
//                VPNManager.getInstance().startVpn(2, "47.88.168.76", "thb2007", "thb2007");
                break;
            case R.id.ll_ip_change://一键换 ip
                isBtnConnect = true;
                mTvReplaceIp.setVisibility(View.VISIBLE);
                mLlIpChange.setEnabled(false);
                mLlIpChange.setBackground(getActivity().getResources().getDrawable(R.drawable.home_fragment_break_bg));
                recLen = 2;
                getCheck1();// 监测账户信息  是否可用
                break;
            case R.id.ll_ip_break:// 断开连接
                isBtnConnect = false;
                mTvLine.setEnabled(true);
                mLlIpSuccess.setVisibility(View.GONE);
                mLlIpChange.setVisibility(View.VISIBLE);
                mTvReplaceIp.setVisibility(View.GONE);
                mHandler.removeMessages(MSG_VPN_CONNECT_TIME);
                stopAnima();
                stopVpn();
                break;
            case ll_ip_reconnect://重新连接
                isBtnConnect = true;
                mTvReplaceIp.setVisibility(View.VISIBLE);
                mLlIpReconnect.setEnabled(false);
                mLlIpChange.setEnabled(false);
                mLlIpChange.setBackground(getActivity().getResources().getDrawable(R.drawable.home_fragment_break_bg));
                mHandler.removeMessages(MSG_VPN_CONNECT_TIME);
                recLen = 2;
                startAnima();
                SoProxy.getInstance().restartProxy();
                break;
            case R.id.iv_close_weixin:
                mRlWeiXin.setVisibility(View.INVISIBLE);
                break;
            case R.id.rl_weixin://点击跳转到微信公众号
//                 UIHelper.goWXPublic("公众号");
                if (EmptyUtils.isNotEmpty(link) && !link.equals("")) {
                    UIHelper.goWebViewIntent(getActivity(), "", link);
                }
                break;
            case R.id.iv_home_kefu:
                String userId = MDUtil.mdEncrypts(String.valueOf(MDUserMgr.getInstance().getId()));
                UIHelper.goWebViewIntent(getActivity(), "售后服务", AppConfig.getInstance().getAppInfo().getServiceUrl() + "&id=" + userId);
                break;
            case R.id.rl_go_bind_phone:
                Intent phone = new Intent(getActivity(), ReplacePhoneActivity.class);
                Bundle phoneb = new Bundle();
                phoneb.putString("phone", userInfo.getPhone());
                phoneb.putString("name", userInfo.getUsername());
                phone.putExtras(phoneb);
                startActivity(phone);
                break;
            case R.id.iv_del:
                mRlGoBindPhone.setVisibility(View.GONE);
                break;
            default:
                break;

        }
    }

    /**
     * 是否走中转线路
     */
    private void isTransitIP() {
        if (isMobile) {
            if (!isTransit) {
                isTransit = true;
                isZhongzhuan = true;
                String ip = mLine.getProxyIp() + ":" + mLine.getProxyPort();
                startVpn(ip);
                return;
            }
        } else {
            LogUtils.e("已断开");
            sendLog(isSuccess ? "1" : "2", isZhongzhuan ? "1" : "2");
            isConnect = false;
            if (isAlreadyConnect) {
                isAlreadyConnect = false;
            }
            updateStopUI();
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final StatsLinePresent present = new StatsLinePresent(getActivity(), new StatsLineInterface() {
            @Override
            public void success(String msg) {

            }

            @Override
            public void error(String msg) {

            }
        });

        SoProxy.getInstance().setProxyListener(new SoListener() {
            @Override
            public void proxyState(SoState soState, SoError soError) {
                switch (soState) {
                    case CONNECTING:
                        Log.e(TAG, "连接中...");
                        break;
                    case CONNECTED:
                        mHandler.sendEmptyMessageDelayed(MSG_VPN_CONNECT_TIME, 1000);
                        Log.e(TAG, "已连接");
                        updateStartUI();
                        isConnect = true;
                        present.getMsg(mId, 1, "");
                        isAlreadyConnect = true;
                        if (modelType.equals("2")) {
                            modelType = "";
                            addIpUse(mModelLine);
                            mLlIpReconnect.setVisibility(View.GONE);
                        }
                        break;
                    case DISCONNECTING:
                        Log.e(TAG, "断开中...");
                        break;
                    case DISCONNECTED:
                        if (isBtnConnect) {
                            LogUtils.e("走中转");
                            isBtnConnect = false;
                            isTransitIP();
                        } else {
                            LogUtils.e("已断开");
                            sendLog(isSuccess ? "1" : "2", isZhongzhuan ? "1" : "2");
                            isConnect = false;
                            if (isAlreadyConnect) {
                                present.getMsg(mId, 2, "");
                                isAlreadyConnect = false;
                            }
                            updateStopUI();
                        }
                        break;
                    case FAIILED:
                        if (isBtnConnect) {
                            isBtnConnect = false;
                            isTransitIP();
                        } else {
                            isConnect = false;
                            if (soError.getCode() != 0) {
                                Log.e(TAG, "code: " + soError.getCode() + ", msg: " + soError.getMsg());
                            }
                            mTvLine.setEnabled(true);
                            ToastUtil.showToast("连接超时");
                            present.getMsg(mId, 4, "");
                            mHandler.removeMessages(MSG_CHECK_TIME_OUT);
                            updateStopUI();
                            stopAnima();
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mTimer != null) {
            mTimer.cancel();
            mTimerTask.cancel();
            mTimer.purge();
        }
        ButterKnife.unbind(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopAnima();
        mHandler.removeMessages(MSG_VPN_CONNECT_TIME);
        mHandler.removeMessages(MSG_VPN_RECONNECT);
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }


    public void updateStartUI() {
        stopAnima();
        mTvReplaceIp.setText("参考归属地:正在获取中... ");
        mTvReplaceIp.setVisibility(View.VISIBLE);
        mLlIpChange.setVisibility(View.GONE);
        mLlIpSuccess.setVisibility(View.VISIBLE);


    }

    public void updateStopUI() {
        mTvReplaceIp.setVisibility(View.GONE);
        mLlIpChange.setVisibility(View.VISIBLE);
        mLlIpSuccess.setVisibility(View.GONE);
    }

    private void startVpn(String ip) {
        if (TextUtils.isEmpty(ip)) {
            ToastUtil.showToast("请选择线路");
            return;
        }
        String username = MDUserMgr.getInstance().getUsername();
        String pwd = EncryptUtils.encryptMD5ToString(MDAccountMgr.getInstance().getLoginPwd() + "zhimadaili").toLowerCase();
        SoProxy.getInstance().setDisallowedPackages(isDis);
        SoProxy.getInstance().startProxy(username,
                pwd, ip);

    }


    private void stopVpn() {
        SoProxy.getInstance().stopProxy();
    }


    /**
     * 此用户是否禁用WeChat QQ
     */
    private void checkDis() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "shield/exclude_shield")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        ToastUtil.showToast(e.getMessage());
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            isDis = false;
                        } else {
                            isDis = true;
                        }
                    }
                });
    }


    /**
     * 实时监测用户信息
     */
    private void getCheck1() {
        HashMap<String, String> map = new HashMap<>();
        map.put("token", MDUtil.mdEncrypt(MDAccountMgr.getInstance().getSessionId()));
        map.put("platform", "android");
        JSONObject jsonObject = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "account/chk_account_enable")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        ToastUtil.showToast(e.getMessage());
                        mTvLine.setEnabled(true);
                        mLlIpChange.setEnabled(true);
                        mLlIpChange.setBackground(getActivity().getResources().getDrawable(R.drawable.btn_white));
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        LogUtils.e(s);
                        if (baseModel.getRet().equals("0")) {
                            if (baseModel.getCode().equals("bind")) {
                                ToastUtil.showToast("绑定手机号送时间哦,骚年快点行动吧!");
                            } else if (baseModel.getCode().equals("recharge")) {
                                ToastUtil.showToast("我就要离你远去,来续费留住我吧!");
                            } else if (baseModel.getCode().equals("1")) {
                            }
                            setLineIp();
                        } else if (baseModel.getRet().equals("1") && baseModel.getCode().equals("timeout")) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                            builder.setMessage(baseModel.getMsg());
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    UIHelper.goLoginPage(getActivity());
                                }
                            });
                            builder.show();
                        } else {
                            ToastUtil.showToast(baseModel.getMsg());
                            mTvReplaceIp.setVisibility(View.GONE);
                            mHandler.removeMessages(MSG_VPN_CONNECT_TIME);
                            stopAnima();
                            stopVpn();
                        }

                    }
                });
    }

    /**
     * 是否是移动网
     */
    private void getIsp() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "dns/get_isp")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            isMobile = true;
                        } else {
                            isMobile = false;
                        }
                    }
                });
    }

    private void sendLog(String status, String transfer) {
        isZhongzhuan = false;
        isSuccess = false;
        Map<String, String> map = new HashMap<>();
        map.put("status", status);
        map.put("transfer", transfer);
        JSONObject json = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "transfer/log")
                .tag(this)
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                    }
                });
    }

    /**
     * 判断连接 vpn 方式(随机或指定线路),连接 vpn
     */
    private void setLineIp() {
        mTvLine.setEnabled(false);//开始连接之前将"线路选择"灰化
        if (isRandom) {
            getRandIp();
        } else {
            startAnima();
            mServerIp = mLine.getIp() + ":" + mLine.getNewPort();
            startVpn(mServerIp);
        }
    }

    /**
     * 随机获取 ip
     */
    private void getRandIp() {
        HashMap<String, String> map = new HashMap<>();
        map.put("session_id", MDAccountMgr.getInstance().getSessionId());
        map.put("platform", "android");
        map.put("is_static", isStatic + "");
        map.put("is_foreign", EmptyUtils.isEmpty(MDModel.getInstance().getIsOpen()) ? "2" : MDModel.getInstance().getIsOpen());
        JSONObject jsonObject = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity())).post(AppContext.getInstance().getBaseUrl() + "server/get_rand_srv_new")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        Gson gson = new Gson();
                        Type LineType = new TypeToken<BaseModel<LineEntity>>() {
                        }.getType();
                        BaseModel<LineEntity> baseModel;
                        try {
                            baseModel = gson.fromJson(s, LineType);
                        } catch (JsonSyntaxException e) {
                            baseModel = gson.fromJson(s, BaseModel.class);
                        }
                        if (baseModel.getRet().equals("0")) {
                            String isOpen = MDModel.getInstance().getIsOpen();
                            mLine = baseModel.getData();
                            mServerIp = baseModel.getData().getIp() + ":" + baseModel.getData().getNewPort();
                            mId = baseModel.getData().getId();
                            if (baseModel.getData().getAgreeType() == null) {
                                mProxyType = 1;
                            } else {
                                if (baseModel.getData().getAgreeType().equals("ss")) {
                                    mProxyType = 2;
                                }
                            }

                            startAnima();
                            startVpn(mServerIp);
                        } else {
                            mTvLine.setEnabled(true);
                            ToastUtil.showToast(baseModel.getMsg());
                            mLlIpChange.setEnabled(true);
                            mLlIpChange.setBackground(getActivity().getResources().getDrawable(R.drawable.btn_bg_white_checks));
                        }

                    }
                });

    }

    public void getIP() {
        mTvReplaceIp.setText("参考归属地: " + defaultIP);
        String userName = MDUserMgr.getInstance().getUsername();
        String phoneNum = MDUserMgr.getInstance().getPhone();
        //本地ip
        String ip = MDUtil.getIPAddress(true);
        String proxyType;
        if (mProxyType == 1) {
            proxyType = "open";
        } else {
            proxyType = "ss";
        }
        Long time = TimeUtils.getCurTimeMills();
        Map<String, String> params = new HashMap<>();
        params.put("username", userName);
        params.put("agreement", proxyType);
        params.put("time", time + "");
        params.put("local_ip", ip);
        params.put("nas_ip", mServerIp);
        params.put("phone", phoneNum);
        params.put("platform", "zhima");
        params.put("client", "android");
        String sign = MDUtil.getSignMD5(params);

        OkGo.getInstance().
                addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post("http://myip.top" + "?username=" + userName + "&client=android&platform=zhima&phone=" + phoneNum
                        + "&nas_ip=" + mServerIp + "&local_ip=" + ip + "&agreement=" + proxyType + "&time=" + time + "&sign=" + sign)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        IpEnetity ipModel = null;
                        try {
                            ipModel = gson.fromJson(s, new TypeToken<IpEnetity>() {
                            }.getType());
                        } catch (Exception e) {
                            try {
                                ipModel = gson.fromJson(s, IpEnetity.class);
                            } catch (Exception exception) {
                                exception.printStackTrace();
                            }
                        }
                        if (ipModel != null) {
//                            mTvReplaceIp.setText("新IP为: " + ipModel.getData().getIp());
                            newIP = ipModel.getIp();
                            mTvReplaceIp.setText("参考归属地: " + newIP + "   " + ipModel.getmProvince() + ipModel.getmCity());
                            newIP = "";
                        } else {
                            mHandler.sendEmptyMessageDelayed(MSG_VPN_GETIP, 1000);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mHandler.sendEmptyMessageDelayed(MSG_VPN_GETIP, 1000);
                    }
                });
    }

    private void startAnima() {
        mTvReplaceIp.setText("正在连接...");
        // 加载动画
        rotate = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_start);
        // 执行动画
        mIvIpStart.startAnimation(rotate);
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(MSG_CHECK_TIME_OUT);
            }
        };
        mTimer.schedule(mTimerTask, TIME_OUT);
    }

    private void stopAnima() {

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }

        if (mLlIpReconnect != null) {
            mLlIpReconnect.setEnabled(true);
            // mLlIpReconnect.setBackground(getActivity().getResources().getDrawable(R.drawable.btn_bg_checks));
        }
        if (mLlIpChange != null) {
            mLlIpChange.setEnabled(true);
            mLlIpChange.setBackground(getActivity().getResources().getDrawable(R.drawable.btn_bg_white_checks));
        }
        if (mIvIpStart != null) {
            mIvIpStart.clearAnimation();
        }
    }

    public void init() {
        mTvValidityTime.setText(MDUserMgr.getInstance().getTime());
//        if (MDUserMgr.getInstance().getLastTime().equals("0")) {
//            mIvHomeKefu.setVisibility(View.GONE);
//        } else {
//            mIvHomeKefu.setVisibility(View.VISIBLE);
//        }
        //   mIvWeixinIcon.setImageBitmap();
        getCode();
    }

    private String link;

    public void getCode() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity())).post(AppContext.getInstance().getBaseUrl() + "account/get_ads_water")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        Gson gson = new Gson();
                        Type userType = new TypeToken<BaseModel<WeiXingImageEntity>>() {
                        }.getType();
                        BaseModel<WeiXingImageEntity> baseModel;
                        try {
                            baseModel = gson.fromJson(s, userType);
                        } catch (JsonSyntaxException e) {
                            baseModel = gson.fromJson(s, BaseModel.class);
                        }
                        if (baseModel.getRet().equals("0")) {
                            String image = baseModel.getData().getImage();
                            link = baseModel.getData().getLink();
                            if (EmptyUtils.isNotEmpty(image)) {
                                mRlWeiXin.setVisibility(View.VISIBLE);
                                Glide.with(getActivity())
                                        .load(image)
                                        .fitCenter()
                                        .into(mIvWeixinIcon);
                            } else {
                                mRlWeiXin.setVisibility(View.INVISIBLE);
                            }


                        } else {
                        }

                    }
                });
    }

    /**
     * 接收 ProvinceAdapter 传来的线路消息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LineEvent event) {
        isRandom = false;
        mTvLine.setText(event.getCity());
        mServerIp = event.getRemoteIp();
//        mServerIp = "61.155.112.149";
        mId = event.getId();
        if (EmptyUtils.isNotEmpty(event.getAgreeType())) {

            if (event.getAgreeType().equals("ss")) {
                mProxyType = 2;
            } else {
                mProxyType = 1;
            }
        }
        modelType = event.getType();
        Logger.e("类型：" + mServerIp);
        if (modelType.equals("2")) {
            mModelLine = event.getModelLine();
            mProxyType = 2;
            getCheck1();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LineEntity event) {
        isRandom = false;
        mTvLine.setText(event.getName());
        mLine = event;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RandomEvent event) {
        if (event.isChangeTitle()) {
            mTvLine.setText("随机选择");
        }
        isStatic = event.isStatic();
        isRandom = event.isRandom();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(MesEvent event) {
        if (event.getMepay() == 1) {
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    //execute the task
                    EventBus.getDefault().post(new MainEvent(1));
                }
            }, 1000);
        }
    }

    /**
     * 获取用户信息
     */
    public void getUserInfo() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "account/get_user_all")
                .tag(getActivity())
                .upJson(mapSession())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Logger.e("用户信息:" + s);
                        Gson gson = new Gson();
                        Type userType = new TypeToken<BaseModel<UserEnetity>>() {
                        }.getType();
                        BaseModel<UserEnetity> baseModel;
                        try {
                            baseModel = gson.fromJson(s, userType);
                        } catch (JsonSyntaxException e) {
                            baseModel = gson.fromJson(s, BaseModel.class);
                        }
                        if (baseModel.getRet().equals("0")) {
                            userInfo = baseModel.getData();
                            if (EmptyUtils.isEmpty(baseModel.getData().getPhone())) {
                                mRlGoBindPhone.setVisibility(View.VISIBLE);
                            } else {
                                mRlGoBindPhone.setVisibility(View.GONE);
                            }

                        } else {
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });
    }

    /**
     * 网络请求参数
     *
     * @return
     */
    private String mapSession() {
        HashMap<String, String> map = new HashMap<>();
        map.put("session_id", MDAccountMgr.getInstance().getSessionId());
        JSONObject json = new JSONObject(map);
        return json.toString();
    }

    /**
     * 添加使用记录
     */
    private void addIpUse(ModelLine modelLine) {
        Map<String, String> map = new HashMap<>();
        map.put("ip_area", "0");
        map.put("ip_expire", "0");
        map.put("ip_used", "0");
        map.put("type", modelLine.getModelType());//	1=芝麻ip库2=使用记录3=我的收藏
        map.put("city_list", "0");
        map.put("ip", mServerIp);
        map.put("line_id", modelLine.getLineId());
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/ip_use_add")
                .tag(this)
                .params(map)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                    }
                });
    }

    /**
     * 获取状态栏高度——方法1
     */
    private void getBarHeight() {
        int statusBarHeight1 = -1;
//获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mRlGoBindPhone.getLayoutParams();
        layoutParams.setMargins(0, statusBarHeight1, 0, 0);
        mRlGoBindPhone.setLayoutParams(layoutParams);
    }
}
